<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本资料</span>
      </div>

      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="登录名称" class="username">
          <el-input v-model="ruleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="ruleForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交修改</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updateUserInfotAPI } from '@/api/index'
export default {
  name: 'user-info',
  data () {
    return {
      ruleForm: {
        username: this.$store.state.userInfo.username,
        nickname: '',
        email: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'change' },
          {
            pattern: /^[a-zA-Z0-9]{1,10}$/,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur' // blur：表单失去焦点
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await updateUserInfotAPI(this.ruleForm)
          console.log(res)
          if (res.status !== 0) {
            return this.$message.error(res.message)
          }
          this.$message.success(res.message)
          // 重新让vuex获取下最新的用户数据
          this.$store.dispatch('getUserInfoActions')
        } else {
          this.$message.error('表单输入有误，请重新输入')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang='less' scoped>
.el-form {
  width: 550px;
}
.username {
  user-select: none;
}
</style>
